package com.businessportal.web.common;

import java.io.*;
import java.text.DecimalFormat;

/**
 * Created by Vadim on 6/26/14.
 */
public class FileSystemHelper {

    public static byte[] readFileStream(final InputStream stream) throws IOException {
        byte[] buffer = new byte[4096];
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        long contentLength = 0;
        int n = 0;
        while (-1 != (n = stream.read(buffer))) {
            contentLength += n;
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }

    public static long readToFile(final InputStream stream, String filePath) throws IOException {
        byte[] buffer = new byte[4096];
        OutputStream output = new FileOutputStream(new File(filePath));
        long contentLength = 0;
        int n = 0;
        while (-1 != (n = stream.read(buffer))) {
            contentLength += n;
            output.write(buffer, 0, n);
        }
        output.flush();
        output.close();
        return contentLength;
    }

    public static String prepareFilePath(String path, String fileExtension){

        String fileName = java.util.UUID.randomUUID().toString() + "." + fileExtension;

        if(fileName == null || path == null)
            return null;

        File fileDir = new File(path);

        if(!fileDir.exists() && !fileDir.mkdirs()){
             return null;
        }

        if(!fileName.isEmpty()){
            return path + File.separator + fileName;
        }

        return null;
    }

/*    public static String readableFileSize(long size) {
        if(size <= 0) return "0";
        final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
        int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }*/
}
